<template>
  <div class="config-list">
    <!-- 搜索和筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="搜索">
          <el-input v-model="searchForm.search" placeholder="配置键/描述" clearable @keyup.enter="handleSearch"
            style="width: 250px" />
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="searchForm.type" placeholder="全部类型" clearable>
            <el-option 
              v-for="option in CONFIG_TYPE_OPTIONS" 
              :key="option.value" 
              :label="option.label" 
              :value="option.value" 
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon>
              <Search />
            </el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon>
              <Refresh />
            </el-icon>
            重置
          </el-button>
          <el-button type="success" @click="handleBatchUpdate" v-if="hasBatchUpdatePermission">
            <el-icon>
              <Edit />
            </el-icon>
            批量更新
          </el-button>
          <el-button type="primary" @click="handleCreate" v-if="hasCreatePermission">
            <el-icon>
              <Plus />
            </el-icon>
            新增配置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 配置列表 -->
    <el-card>
      <el-table v-loading="loading" :data="configList" stripe style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="key" label="配置键" width="200" />
        <el-table-column prop="value" label="配置值" width="200">
          <template #default="{ row }">
            <el-tooltip :content="row.value" placement="top" v-if="row.value && row.value.length > 20">
              <span>{{ row.value.substring(0, 20) }}...</span>
            </el-tooltip>
            <span v-else>{{ row.value }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" />
        <el-table-column label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getConfigTypeTagType(row.type)">
              {{ getConfigTypeText(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)" v-if="hasEditPermission">
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)"
              v-if="hasDeletePermission">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          :current-page="pagination.page"
          :page-size="pagination.limit"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 配置表单对话框 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑配置' : '新增配置'" width="600px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="配置键" prop="key">
          <el-input v-model="form.key" placeholder="请输入配置键" :disabled="isEdit" />
        </el-form-item>

        <el-form-item label="配置值" prop="value">
          <el-input v-if="form.type === 'STRING'" v-model="form.value" type="textarea" :rows="3" placeholder="请输入配置值" />
          <el-input-number v-else-if="form.type === 'NUMBER'" v-model="form.value" placeholder="请输入数字"
            style="width: 100%" />
          <el-switch v-else-if="form.type === 'BOOLEAN'" v-model="form.value" active-text="是" inactive-text="否" />
          <el-input v-else-if="form.type === 'JSON'" v-model="form.value" type="textarea" :rows="5"
            placeholder="请输入JSON格式的配置值" />
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="2" placeholder="请输入描述" />
        </el-form-item>

        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型" :disabled="isEdit">
            <el-option 
              v-for="option in CONFIG_TYPE_OPTIONS" 
              :key="option.value" 
              :label="option.label" 
              :value="option.value" 
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 批量更新对话框 -->
    <el-dialog v-model="batchDialogVisible" title="批量更新配置" width="800px">
      <el-form :model="batchForm" label-width="100px">
        <el-form-item label="配置列表">
          <div class="batch-configs">
            <div v-for="(config, index) in batchForm.configs" :key="index" class="batch-config-item">
              <el-input v-model="config.key" placeholder="配置键" style="width: 200px" />
              <el-input v-model="config.value" placeholder="配置值" style="width: 300px" />
              <el-input v-model="config.description" placeholder="描述" style="width: 200px" />
              <el-button type="danger" @click="removeBatchConfig(index)" size="small">
                删除
              </el-button>
            </div>
          </div>
          <el-button type="primary" @click="addBatchConfig" style="margin-top: 10px">
            添加配置
          </el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleBatchSubmit" :loading="batchLoading">
            批量更新
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Plus, Edit, Search, Refresh } from '@element-plus/icons-vue'
import { systemApi } from '@/api'
import { useUserStore } from '@/stores/user'
import type { SystemConfig } from '@/types'
import { formatDate } from '@/utils/format'
import { ALL_PERMISSIONS } from '@/constants/permissions'
import { 
  CONFIG_TYPE_OPTIONS,
  getConfigTypeTagType,
  getConfigTypeText
} from '@/constants/common'
import { computed } from 'vue'

const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const configList = ref<SystemConfig[]>([])
const searchForm = reactive({
  search: '',
  type: ''
})

const pagination = reactive({
  page: 1,
  limit: 20,
  total: 0
})

// 表单相关
const dialogVisible = ref(false)
const submitLoading = ref(false)
const isEdit = ref(false)
const formRef = ref<FormInstance>()
const form = reactive({
  key: '',
  value: '',
  description: '',
  type: 'STRING'
})

// 批量更新相关
const batchDialogVisible = ref(false)
const batchLoading = ref(false)
const batchForm = reactive({
  configs: [
    { key: '', value: '', description: '' }
  ]
})

// 表单验证规则
const rules: FormRules = {
  key: [
    { required: true, message: '请输入配置键', trigger: 'blur' }
  ],
  value: [
    { required: true, message: '请输入配置值', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择类型', trigger: 'change' }
  ]
}

// 权限检查
const hasBatchUpdatePermission = computed(() => userStore.hasPermission(ALL_PERMISSIONS.SYSTEM_CONFIG_UPDATE));
const hasCreatePermission = computed(() => userStore.hasPermission(ALL_PERMISSIONS.SYSTEM_CONFIG_CREATE));
const hasEditPermission = computed(() => userStore.hasPermission(ALL_PERMISSIONS.SYSTEM_CONFIG_UPDATE));
const hasDeletePermission = computed(() => userStore.hasPermission(ALL_PERMISSIONS.SYSTEM_CONFIG_DELETE));

// 获取配置列表
const fetchConfigs = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      limit: pagination.limit,
      ...searchForm
    }
    const response = await systemApi.config.getList(params)
    configList.value = response.data.data
    pagination.total = response.data.pagination.total
    pagination.page = response.data.pagination.page
    pagination.limit = response.data.pagination.limit
  } catch (error) {
    ElMessage.error('获取配置列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchConfigs()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    search: '',
    type: ''
  })
  pagination.page = 1
  fetchConfigs()
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.limit = size
  pagination.page = 1
  fetchConfigs()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  fetchConfigs()
}

// 新增配置
const handleCreate = () => {
  isEdit.value = false
  Object.assign(form, {
    key: '',
    value: '',
    description: '',
    type: 'STRING'
  })
  dialogVisible.value = true
}

// 编辑配置
const handleEdit = (row: SystemConfig) => {
  isEdit.value = true
  Object.assign(form, {
    key: row.key,
    value: row.value,
    description: row.description || '',
    type: row.type
  })
  dialogVisible.value = true
}

// 删除配置
const handleDelete = async (row: SystemConfig) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除配置 "${row.key}" 吗？此操作不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await systemApi.config.delete(row.id)
    ElMessage.success('删除成功')
    fetchConfigs()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitLoading.value = true

    const submitData = {
      key: form.key,
      value: form.value,
      description: form.description,
      type: form.type as 'STRING' | 'NUMBER' | 'BOOLEAN' | 'JSON'
    }

    if (isEdit.value) {
      // 编辑时需要先获取配置ID
      const config = configList.value.find(c => c.key === form.key)
      if (config) {
        await systemApi.config.update(config.id, submitData)
        ElMessage.success('配置更新成功')
      }
    } else {
      await systemApi.config.create(submitData)
      ElMessage.success('配置创建成功')
    }

    dialogVisible.value = false
    fetchConfigs()
  } catch (error) {
    console.error('提交失败:', error)
  } finally {
    submitLoading.value = false
  }
}

// 批量更新
const handleBatchUpdate = () => {
  batchDialogVisible.value = true
  batchForm.configs = [
    { key: '', value: '', description: '' }
  ]
}

// 添加批量配置项
const addBatchConfig = () => {
  batchForm.configs.push({ key: '', value: '', description: '' })
}

// 删除批量配置项
const removeBatchConfig = (index: number) => {
  batchForm.configs.splice(index, 1)
}

// 批量提交
const handleBatchSubmit = async () => {
  const validConfigs = batchForm.configs.filter(config => config.key && config.value)

  if (validConfigs.length === 0) {
    ElMessage.warning('请至少添加一个有效配置')
    return
  }

  try {
    batchLoading.value = true
    await systemApi.config.batchUpdate(validConfigs)
    ElMessage.success('批量更新成功')
    batchDialogVisible.value = false
    fetchConfigs()
  } catch (error) {
    ElMessage.error('批量更新失败')
  } finally {
    batchLoading.value = false
  }
}



// 初始化
onMounted(() => {
  fetchConfigs()
})
</script>

<style scoped>
.config-list {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.batch-configs {
  max-height: 400px;
  overflow-y: auto;
}

.batch-config-item {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
  align-items: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>